package com.suixun.utils;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import io.jsonwebtoken.*;
import io.jsonwebtoken.impl.crypto.MacProvider;

import java.util.Date;

public class JWTHelper {

    String apiKey = "!2#4%6&8";
    public String createJWT(String id, String issuer, String subject, long ttlMillis,String audience) {
        // The JWT signature algorithm we will be using to sign the token
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;

        long nowMillis = System.currentTimeMillis();
        Date now = new Date(nowMillis);

        // We will sign our JWT with our ApiKey secret
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey);
        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());

        // Let's set the JWT Claims
        JwtBuilder builder =
                Jwts.builder().setId(id).setIssuedAt(now).setSubject(subject).setIssuer(issuer).setAudience(audience)
                        .signWith(signatureAlgorithm, signingKey);

        // if it has been specified, let's add the expiration
        if (ttlMillis > 0l) {
            long expMillis = nowMillis + ttlMillis;
            Date exp = new Date(expMillis);
            builder.setExpiration(exp);
        }

        // Builds the JWT and serializes it to a compact, URL-safe string
        return builder.compact();
    }

    public Claims parseJWT(String jwt) {
        // This line will throw an exception if it is not a signed JWS (as expected)
        Claims claims =
                Jwts.parser()
                        .setSigningKey(DatatypeConverter.parseBase64Binary(apiKey))
                        .parseClaimsJws(jwt).getBody();
        /*System.out.println("ID: " + claims.getId());
        System.out.println("Subject: " + claims.getSubject());
        System.out.println("Issuer: " + claims.getIssuer());
        System.out.println("Expiration: " + claims.getExpiration());*/
        return claims;
    }

    public static void main(String[] args) {
        JWTHelper jWTHelper = new JWTHelper();
        String jwtstr = jWTHelper.createJWT("1","suixun","testname testpassword",0l,"guardian");
        jWTHelper.parseJWT(jwtstr);
        
        try {
            jWTHelper.parseJWT("aaaaaaaaaaaa");
        } catch (Exception e) {
            System.out.print("error");
        }
        
        try {
            Key key = MacProvider.generateKey();

            String s =
                    Jwts.builder().setSubject("Joe").signWith(SignatureAlgorithm.HS512, key)
                            .compact();
            String b = Jwts.parser().setSigningKey(key).parseClaimsJws(s).getBody().getSubject();
            System.out.print(b);
        } catch (SignatureException e) {

            // don't trust the JWT!
        }
        System.out.print("test");
    }
}
